package com.example.studentdemo.aspect;

import com.example.studentdemo.annotation.RequiresRole;
import com.example.studentdemo.entity.Account;
import com.example.studentdemo.constant.RoleConstant;
import com.example.studentdemo.exception.CustomerException;
import com.example.studentdemo.utils.TokenUtils;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Pointcut;
import org.aspectj.lang.reflect.MethodSignature;
import org.springframework.stereotype.Component;

import java.lang.reflect.Method;

@Aspect
@Component
public class PermissionAspect {

    @Pointcut("@annotation(com.example.studentdemo.annotation.RequiresRole)")
    public void permissionPointCut() {}

    @Around("permissionPointCut()")
    public Object around(ProceedingJoinPoint point) throws Throwable {
        // 获取当前用户
        Account currentUser = TokenUtils.getCurrentUser();
        if (currentUser == null) {
            throw new CustomerException("401", "未登录或登录已过期");
        }

        // 获取方法上的注解
        MethodSignature signature = (MethodSignature) point.getSignature();
        Method method = signature.getMethod();
        RequiresRole annotation = method.getAnnotation(RequiresRole.class);

        // 获取注解中的角色和权限
        String[] roles = annotation.roles();

        // 如果有角色要求，则检查用户角色是否匹配
        if (roles.length > 0) {
            boolean hasPermission = false;
            for (String role : roles) {
                // 使用枚举类进行类型安全的角色检查
                RoleConstant roleConstant = RoleConstant.getByRole(role);
                if (roleConstant != null && roleConstant.getRole().equals(currentUser.getRole())) {
                    hasPermission = true;
                    break;
                }
            }
            if (!hasPermission) {
                throw new CustomerException("403", "没有足够的权限执行此操作");
            }
        }

        // 执行原方法
        return point.proceed();
    }
}